package com.peanut.huibutie.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.google.common.annotations.VisibleForTesting;
import com.peanut.huibutie.openapi.Cashier;
import com.peanut.huibutie.openapi.GetAccessTokenByAuthCode;
import com.peanut.huibutie.common.AppConfig;
import com.peanut.huibutie.common.UserContext;
import com.peanut.huibutie.entity.OrderVO;
import com.peanut.huibutie.entity.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 模拟一个应用页面，可以用这个页面 与 会补贴 交互 ，进行直观的测试。
 */
@VisibleForTesting
@Controller
@RequestMapping("/h5demo")
@Slf4j
public class AppH5DemoController {

    @Autowired
    GetAccessTokenByAuthCode getAccessTokenByAuthCode;
    @Resource
    private AppConfig appConfig;
    @Resource
    private UserContext userContext;
    @Resource
    private Cashier cashier;

    /**
     * 应用首页（模拟的），接收 会补贴 的 auth_code，然后 程序换取 access_token
     * <p>http://localhost:8081/h5demo?auth_code=sadftest</p>
     *
     * @param authCode
     * @return
     */
    @GetMapping()
    public void index(@RequestParam("auth_code") String authCode, HttpServletResponse response) {

        log.info("会补贴请求过来的auth_code=" + authCode);
        StringBuilder html = new StringBuilder();
        try {
            getAccessTokenByAuthCode.invoke(authCode);
            UserVO context = userContext.getContext();
            if (null == context) {
                throw new Exception("当前用户是null。换取token失败了");
            }
//        userContext.getContext().getOpenId()
            html.append("<h5>openId:</h5><p>").append(context.getOpenId())
                    .append("</p><h5>access_token:</h5><p>").append(context.getAccessToken())
                    .append("</p><form method=post><input type=submit value=模拟-创建订单-去会补贴支付></input></form>");
        } catch (Exception e) {
            e.printStackTrace();
            html.append(String.format("<h5>%s</h5>", ExceptionUtils.getMessage(e)));
        }
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(html5.replace("[data]", html.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }
        return;
    }

    /**
     * 用户在页面支付， 获取并跳转到 会补贴 的收银台。
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping
    public String pay(HttpServletRequest request, HttpServletResponse response) {
        log.info("模拟-创建订单-去会补贴支付");
        if (1 == 2) {
//            response.setStatus(302);
//            return "https//www.baidu.com/";
//            return "http://localhost:8081/h5demo/test";
            return "redirect:h5demo/test?abc";
        }

//        try {
        OrderVO orderVO = new OrderVO();
        orderVO.setOuterOrderNo("" + System.currentTimeMillis())
                .setOrderAmt(RandomUtil.randomLong(5, 200))
                .setAttach("SDK测试")
                .setNotifyUrl("http://localhost:8081/notify/pay_notify")
                .setOrderTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        String url = cashier.invoke(orderVO);
        log.info("调用API获取收银台地址，url={}", url);
        response.setStatus(302);
        return "redirect:" + url;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ExceptionUtils.getMessage(e);
//        }
    }

    /**
     * 这个没有用。仅仅是个临时测试页面
     *
     * @param request
     * @return
     */
    @ResponseBody
    @GetMapping("/test")
    public String test(HttpServletRequest request) {
        return "this is the test page - " + request.getQueryString();
    }

    private static String html5 = "<!DOCTYPE html>\n" +
            "<html>\n" +
            "\n" +
            "<head>\n" +
            "  <meta charset=\"UTF-8\">\n" +
            "  <title>HTML5 Demo</title>\n" +
            "  <meta charset=\"utf-8\" />\n" +
            "  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge,chrome=1\">\n" +
            "  <meta name=\"viewport\" content=\"maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width=device-width\">\n" +
            "  <style>\n" +
            "    * {\n" +
            "      margin: 0;\n" +
            "      padding: 0;\n" +
            "    }\n" +
            "\n" +
            "    html,\n" +
            "    body {\n" +
            "      padding: 20px;\n" +
            "      font-size: 10px;\n" +
            "      width: 100%;\n" +
            "      height: 100%;\n" +
            "      display: flex;\n" +
            "      flex-direction: column;\n" +
            "      align-items: center;\n" +
            "      box-sizing: border-box;\n" +
            "    }\n" +
            "\n" +
            "    div,\n" +
            "    h5,\n" +
            "    p {\n" +
            "      box-sizing: border-box;\n" +
            "      word-break: break-word;\n" +
            "      width: 100%;\n" +
            "    }\n" +
            "\n" +
            "    h5 {\n" +
            "      margin-bottom: .5rem;\n" +
            "      text-align: center;\n" +
            "      font-size: 2rem;\n" +
            "    }\n" +
            "\n" +
            "    p {\n" +
            "      margin-bottom: .5rem;\n" +
            "      text-align: center;\n" +
            "      font-size: 1.5rem;\n" +
            "    }\n" +
            "\n" +
            "    input[type='submit'] {\n" +
            "      margin-top: 1rem;\n" +
            "      font-size: 1.5rem;\n" +
            "      padding: 1.5rem;\n" +
            "    }\n" +
            "\n" +
            "    .title {\n" +
            "      margin-bottom: 2rem;\n" +
            "      color: red;\n" +
            "    }\n" +
            "  </style>\n" +
            "</head>\n" +
            "\n" +
            "<body>\n" +
            "  <h5 class=\"title\">Hello, 我是一个demo商家应用的页面哈</h5>\n" +
            "[data]" +
            "</body>\n" +
            "\n" +
            "</html>";
}
